﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace XYZshell.Game.CardGameEngine
{
	/// <summary>
	/// 条件表达式参数
	/// </summary>
	public  class ExpressionParam:IXMLable,INamed
	{
		public ExpressionParam()
		{
		}

		public ExpressionParam(string name,string valueStr,ExpressionParamType paramType,string typeStr)
		{
			this.Name = name;
			this.ValueString = valueStr;
			this.ParamType = paramType;
			this.TypeString = typeStr;

		}
		/// <summary>
		/// 参数名称
		/// </summary>
		public string Name
		{
			get;
			set;
		}
		/// <summary>
		/// 参数值字符串形式
		/// </summary>
		public string ValueString
		{
			get;
			set;
		}
		/// <summary>
		/// 参数值的类型
		/// </summary>
		public ExpressionParamType ParamType
		{
			get;
			set;
		}

		/// <summary>
		/// 参数类型字符串
		/// </summary>
		public string TypeString
		{
			get;
			set;
		}

		public Type Type
		{
			get
			{
				return Type.GetType( TypeString );
			}
			set
			{
				TypeString = value.ToString();
			}
		}

		/// <summary>
		/// 只读,获取参数的运行时值
		/// </summary>
		public object Value
		{
			get
			{
				switch (ParamType)
				{
					case ExpressionParamType.Standard:
						Type t=Type.GetType( TypeString, true, true );
						return Convert.ChangeType(ValueString, t );
					case ExpressionParamType.Path:
						return GameContext.Find( ValueString );
				}
				throw new Exception( "解析参数出错" );
			}
		}



		///// <summary>
		///// 转换为参数值的运行时类型
		///// </summary>
		//public Type TypeValue
		//{
		//    get;
		//    set;
		//}

		#region IXMLable 成员

		/// <summary>
		/// 转换为XML
		/// </summary>
		/// <returns></returns>
		public string ToXML()
		{
			if (TypeString != null)
			{
				return string.Format( "<param name='{0}' value='{1}' type='{2}' typeString='{3}' />", Name, ValueString, this.ParamType.ToString().ToLower(),TypeString );
			}
			return string.Format( "<param name='{0}' value='{1}' type='{2}'/>", Name, ValueString, this.ParamType.ToString().ToLower() );
		}

		/// <summary>
		/// 从XML中生成条件表达式参数
		/// </summary>
		/// <param name="xmlNode"></param>
		/// <returns></returns>
		public static  ExpressionParam FromXML( string xmlNode )
		{
			try
			{
				XObject xo=new XObject( xmlNode );
				ExpressionParam ep=new ExpressionParam();
				ep.Name = xo.Name;
				ep.TypeString = xo.Attribute( "typeString" );
				ep.ValueString = xo.Value;
				ep.ParamType = (ExpressionParamType)Enum.Parse( typeof( ExpressionParamType ), xo.Type,true );
				return ep;
			}
			catch (Exception ex)
			{
				throw new Exception(  ex.Message + "ExpressionParam:从XML中生成条件表达式参数出错");
			}
		}

		#endregion
	}
}
